<?php
/**
 * User: krisbuist
 * Date: 1/19/12
 * Time: 2:53 PM
 */

require_once APPPATH . 'core/controller.php';

class AuthController extends Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->data['styles'][] = '/public/css/auth-register.css';
        $this->load->library('form_validation');
    }

    public function login()
    {
        if (!$this->input->post('loginForm'))
        {
            $this->parser->parse('auth/login.tpl', $this->data);
        }
        else
        {
            $this->processLogin();
        }
    }

    private function processLogin()
    {
        $username = $this->input->post('username', true);
        $password = $this->input->post('password', true);
        $password2 = sha1($password);

        $query = $this->em->createQuery("SELECT u FROM User u WHERE u.username = :username AND (u.password = :password OR u.password = :password2)")->setMaxResults(1);
        $query->setParameter('username', $username);
        $query->setParameter('password', $password);
        $query->setParameter('password2', $password2);

        $user = $query->getOneOrNullResult();

        if (sizeof($user) == 0)
        {
            $this->data['errorMessage'] = 'De combinatie van gebruikersnaam en wachtwoord is niet gevonden';
            $this->parser->parse('auth/login.tpl', $this->data);
        }
        else
        {
            $this->session->set_userdata('loggedin', true);
            $this->session->set_userdata('username', $user->getUsername());
            $this->session->set_userdata('userId', $user->getId());
            $this->session->set_userdata('accessLevel', $user->getType()->getAccessLevel());

            redirect("/", "Location");
        }
    }

    public function logout()
    {
        $this->session->unset_userdata('loggedin');
        $this->session->unset_userdata('user');
        $this->session->unset_userdata('accessLevel');
        $this->session->sess_destroy();
        redirect("/", "Location");
    }

    public function register()
    {
        if (!$this->input->post('submit'))
        {
            $this->parser->parse('auth/register.tpl', $this->data);
        }
        else
        {
            $this->processRegistration();
        }
    }

    public function registerStandard()
    {
        $this->data['accountType'] = 1;
        $this->parser->parse('auth/registerForm.tpl', $this->data);
    }

    public function registerPro()
    {

        $this->data['accountType'] = 2;
        $this->parser->parse('auth/registerForm.tpl', $this->data);
    }


    /**
     * @var CI_Form_Validation
     */
    public $form_validation;

    public function processRegistration()
    {
        $this->setValidationRules();
        $this->form_validation->set_error_delimiters('<span class="help-inline">', '</span>');
        $this->form_validation->set_message('required', 'Het veld %s is vereist om te registreren');
        $this->form_validation->set_message('matches', 'De twee wachtwoordvelden komen niet overeen');
        $this->form_validation->set_message('valid_email', 'Voer een geldig emailadres is om te registreren');

        if ($this->form_validation->run() == FALSE)
        {
            if ($this->input->post('accountType') == 2)
            {
                $this->registerPro();
            }
            else
            {
                $this->registerStandard();
            }
        }
        else
        {
            $this->persistNewUser();
        }

    }

    public function setValidationRules()
    {
        $this->form_validation->set_rules('firstName', 'Voornaam', 'trim|required');
        $this->form_validation->set_rules('lastName', 'Achternaam', 'trim|required');
        $this->form_validation->set_rules('gender', 'Geslacht', 'trim|required');
        $this->form_validation->set_rules('email', 'Emailadres', 'trim|required|valid_email');
        $this->form_validation->set_rules('username', 'Gebruikersnaam', 'trim|required');
        $this->form_validation->set_rules('password', 'Wachtwoord', 'trim|required|matches[passwordConfirmation]|sha1');
        $this->form_validation->set_rules('passwordConfirmation', 'Wachtwoordbevestiging', 'trim|required');

        if ($this->input->post('accountType') == 2)
        {
            $this->form_validation->set_rules('bankAccount', 'Rekeningnummer', 'trim|required');
            $this->form_validation->set_rules('agreePayment', 'Toestemming voor Automatische Incasso', 'required');
        }
    }

    private function persistNewUser()
    {
        $newUser = new User();
        $newUser->setName($this->input->post('firstName') . " " . $this->input->post('lastName'));
        $newUser->setGender($this->input->post('gender'));
        $newUser->setEmail($this->input->post('email'));
        $newUser->setUsername($this->input->post('username'));
        $newUser->setPassword($this->input->post('password'));

        if ($this->input->post('accountType') == 2)
        {
            $newUser->setBankAccount($this->input->post('bankAccount'));
        }

        $accountType = $this->em->find('Account_Type', $this->input->post('accountType'));
        $newUser->setType($accountType);

        $this->em->persist($newUser);
        $this->em->flush();

        redirect("/", "Location");
    }
}
